package org.wxd.bi.api;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.wxd.bi.api.struct.PushMapping;
import org.wxd.net.ssl.SslProtocolType;
import org.wxd.net.web.hs.util.HttpPost;
import org.wxd.str.json.Object2Json;

import java.io.Serializable;
import java.util.Collection;

/**
 * @author: Troy.Chen(無心道, 15388152619)
 * @version: 2021-10-12 14:36
 **/
public class PushApiHttp extends PushApi implements Serializable {

    private static final long serialVersionUID = 1L;
    private static final Logger log = LoggerFactory.getLogger(PushApiHttp.class);

    private String apiAddress = "https://127.0.0.1:18601/";

    public PushApiHttp(int appId, String token) {
        super(appId, token);
    }

    public PushApiHttp(int appId, String token, String apiAddress) {
        super(appId, token);
        this.apiAddress = apiAddress;
    }

    public String getApiAddress() {
        return apiAddress;
    }

    public PushApiHttp setApiAddress(String apiAddress) {
        if (!apiAddress.endsWith("/")) apiAddress += "/";
        this.apiAddress = apiAddress;
        return this;
    }

    HttpPost httpClient(String uri) {
        return HttpPost.of(uri)
                .setTimeOut(5000, 0)
                .setSslProtocolType(SslProtocolType.TLSV12)
                .addTextParam("appId", String.valueOf(this.appId))
                .addTextParam("token", this.token);
    }

    @Override
    protected void pushMapping0(PushMapping build) {
        String uri = apiAddress + "push/mapping";
        String runResult = httpClient(uri)
                .addTextParam("mapping", build.toJson())
                .request()
                .bodyString();
        printRunResult(runResult);
    }

    @Override
    public void pushData(String tableName, String data) {
        if (isBatch()) {
            super.pushData(tableName, data);
        } else {
            String uri = apiAddress + "push/data";
            String runResult = httpClient(uri)
                    .addTextParam("tableName", tableName)
                    .addTextParam("data", data)
                    .request()
                    .bodyString();
            printRunResult(runResult);
        }
    }

    @Override
    protected void pushData(String tableName, Collection<String> datas) {
        String uri = apiAddress + "push/datas";
        String runResult = httpClient(uri)
                .addTextParam("tableName", tableName)
                .addTextParam("datas", Object2Json.toJson(datas))
                .request()
                .bodyString();
        printRunResult(runResult);
    }

}
